package com.admin.system.modules.mnt.rest;

import com.admin.common.utils.PageResult;
import com.admin.component.web.MultipartFileUtil;
import com.admin.logging.annotation.Log;
import com.admin.logging.enums.OperateTypeEnum;
import com.admin.system.modules.mnt.dto.DeployHistoryQueryDTO;
import com.admin.system.modules.mnt.entity.DeployHistory;
import com.admin.system.modules.mnt.service.DeployHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author sq-lan
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "运维：部署历史管理")
@RequestMapping("/api/deployHistory")
public class DeployHistoryController {

    private final DeployHistoryService deployhistoryService;

    @ApiOperation(value = "查询部署历史")
    @GetMapping
    @PreAuthorize("@ss.check('deployHistory:list')")
    public ResponseEntity<PageResult<DeployHistory>> paging(DeployHistoryQueryDTO dto) {
        return new ResponseEntity<>(deployhistoryService.paging(dto), HttpStatus.OK);
    }

    @Log(module = "部署历史管理", operateType = OperateTypeEnum.REMOVE)
    @ApiOperation(value = "删除部署历史")
    @DeleteMapping
    @PreAuthorize("@ss.check('deployHistory:del')")
    public ResponseEntity<Object> remove(@RequestBody Set<String> ids) {
        deployhistoryService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("导出部署历史数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@ss.check('deployHistory:list')")
    public void exportDeployHistory(HttpServletResponse response, DeployHistoryQueryDTO dto) throws IOException {
        List<DeployHistory> list = deployhistoryService.list(dto);
        List<Map<String, Object>> result = new ArrayList<>();
        for (DeployHistory deployHistory : list) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("部署编号", deployHistory.getDeployId());
            map.put("应用名称", deployHistory.getAppName());
            map.put("部署IP", deployHistory.getIp());
            map.put("部署时间", deployHistory.getDeployDate());
            map.put("部署人员", deployHistory.getDeployUser());
            result.add(map);
        }
        MultipartFileUtil.downloadExcel(result, response);
    }

}
